<template>
  <MainContainer class="p-5">
    <el-button type="primary" @click="openDialog()">添加任务</el-button>
    <MyTable
      v-loading="loading"
      data-test="my-table"
      class="my-2"
      :data="list"
      :columns="columns"
      :is-show-selection="false"
    ></MyTable>
    <el-pagination
      v-model:currentPage="params.page"
      v-model:page-size="params.limit"
      data-test="task-pagination"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="justify-end"
      @size-change="handleQuery"
      @current-change="handleQuery"
    />
    <MyFormDialog
      v-model:visible="dialogVisible"
      v-model:formData="formData"
      :title="dialogTitle"
      :options="dialogOptions"
      :loading="loading"
      @confirm="handleConfirm"
    ></MyFormDialog>
  </MainContainer>
</template>
<script lang="jsx" setup>
import useCRUD from "@/composables/useCRUD.js";
import MainContainer from "@/components/MainContainer.vue";
import MyFormDialog from "@/components/MyFormDialog.vue";
import MyTable from "@/components/MyTable.vue";
import { getCompanyRobotList } from "@/api/disinfect/robot-manage";
import { getDisinfectPath } from "@/api/robot-disinfect-map";
import {
  getDisinfectTask,
  createDisinfectTask,
  deleteDisinfectTask,
  updateDisinfectTask,
  activationDisinfectTask,
} from "@/api/robot-disinfect-task";
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { rules, halfway, format } from "./utils.js";
import { disinfectTask } from "@/api/disinfect/task-manage";

// 弹窗配置
const dialogOptions = [
  { prop: "name", label: "任务名称", rules },
  {
    prop: "rid",
    label: "防疫机器人",
    rules,
    customRender() {
      return (
        <el-select class="w-full">
          {optionData.robot.map((item) => {
            return (
              <el-option
                data-test="robot-list"
                label={item.name}
                value={item.code}
              ></el-option>
            );
          })}
        </el-select>
      );
    },
  },
  {
    prop: "tid",
    label: "消毒路径",
    rules,
    customRender() {
      return (
        <el-select class="w-full" multiple>
          {optionData.path.map((item) => {
            return (
              <el-option
                data-test="disinfection-path-list"
                label={item.name}
                value={item.id}
              ></el-option>
            );
          })}
        </el-select>
      );
    },
  },
  {
    prop: "halfwayWay",
    label: "途中消毒方式",
    rules,
    customRender() {
      return (
        <el-radio-group>
          {halfway.map((item) => (
            <el-radio-button label={item.value}>{item.name}</el-radio-button>
          ))}
        </el-radio-group>
      );
    },
  },
  {
    prop: "targetWay",
    label: "目标消毒方式",
    rules,
    customRender() {
      return (
        <el-radio-group>
          {halfway.map((item) => (
            <el-radio-button label={item.value}>{item.name}</el-radio-button>
          ))}
        </el-radio-group>
      );
    },
  },
  {
    prop: "fog",
    label: "雾化剂量",
    rules,
    customRender() {
      return <el-slider class="mx-2" />;
    },
  },
  { prop: "retentionTime", label: "停留时间（秒）", rules },
  {
    prop: "uvProtection",
    label: "紫外线安全保护",
    rules,
    customRender() {
      return (
        <el-radio-group>
          <el-radio label={1}>是</el-radio>
          <el-radio label={0}>否</el-radio>
        </el-radio-group>
      );
    },
  },
  {
    prop: "startTime",
    label: "任务执行时间",
    rules,
    customRender() {
      return (
        <el-date-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
      );
    },
  },
  {
    prop: "condition",
    label: "任务激活条件",
    rules,
    customRender() {
      return (
        <el-select class="w-full">
          <el-option value={0} label="单次" />
          <el-option value={1} label="每天" />
          <el-option value={2} label="工作日" />
          <el-option value={3} label="节假日" />
        </el-select>
      );
    },
  },
];

const columns = [
  { prop: "name", label: "任务名称" },
  { prop: "rid", label: "机器人编码" },
  {
    prop: "halfwayWay",
    label: "途中消毒方式",
    formatter(row) {
      return format.halfway(row.halfwayWay);
    },
  },
  {
    prop: "targetWay",
    label: "目标消毒方式",
    formatter(row) {
      return format.halfway(row.targetWay);
    },
  },
  { prop: "fog", label: "雾化剂量" },
  { prop: "retentionTime", label: "停留时间" },
  { prop: "startTime", label: "执行时间" },
  {
    prop: "uvProtection",
    label: "紫外线安全保护",
    formatter(row) {
      return row.uvProtection ? "是" : "否";
    },
  },
  {
    prop: "condition",
    label: "工作周期",
    formatter(row) {
      return format.condition(row.condition);
    },
  },
  {
    prop: "status",
    label: "任务状态",
    formatter(row) {
      return row.status ? "已开始" : "未开始";
    },
  },
  {
    prop: "activeStatus",
    label: "激活状态",
    formatter(row) {
      return row.activeStatus ? "已激活" : "未激活";
    },
  },
  {
    label: "操作",
    prop: "action",
    minWidth: 100,
    customRender(row) {
      return (
        <div data-test="handle-btn">
          <el-button
            type="primary"
            link
            onClick={() => openDialog(row.id, row)}
          >
            编辑
          </el-button>
          <el-button
            v-show={!row.activeStatus}
            link
            type="success"
            onClick={() => activeState(row.id)}
          >
            激活
          </el-button>
          <el-button
            link
            type="danger"
            onClick={async () => {
              await ElMessageBox.confirm("确认继续操作吗", "警告");
              const { message } = await handleDelete(row.id);
              ElMessage({ type: "success", message });
            }}
          >
            删除
          </el-button>
        </div>
      );
    },
  },
];

const optionData = reactive({
  robot: [],
  path: [],
});
async function initData() {
  const {
    data: { list: list1 = [] },
  } = await getCompanyRobotList({ page: 1, limit: 100 });
  optionData.robot = list1;
  const {
    data: { list: list2 = [] },
  } = await getDisinfectPath();
  optionData.path = list2;
}
initData();

//获取单条数据
const formData = ref({});
const dialogTitle = ref("");

function openDialog(id) {
  formData.value.type = 0;
  dialogTitle.value = id ? "编辑" : "新增";
  if (id) getOne(id);
  dialogVisible.value = true;
}

async function getOne(id) {
  const { data } = await disinfectTask.query(id);
  data.tid = data.tid.split(",").map(Number);
  data.uvProtection = Number(data.uvProtection);
  formData.value = { type: 0, ...data };
}

// 激活任务
async function activeState(id) {
  await ElMessageBox.confirm("确认继续操作吗", "警告");
  const { message } = await activationDisinfectTask(id);
  ElNotification({ title: "提示", type: "success", message });
  handleQuery();
}

function handleConfirm(data) {
  data.tid = data.tid.toString();
  if (data.id) {
    handleUpdate(data.id, data);
  } else {
    handleCreate(data);
  }
}

const crudOptions = {
  queryApi: getDisinfectTask,
  createApi: createDisinfectTask,
  deleteApi: deleteDisinfectTask,
  updateApi: updateDisinfectTask,
};
const {
  params,
  handleQuery,
  list,
  loading,
  dialogVisible,
  handleDelete,
  total,
  handleUpdate,
  handleCreate,
} = useCRUD(crudOptions);

handleQuery();
</script>
